package com.example.test6;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.webkit.URLUtil;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.google.android.material.textfield.TextInputLayout;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;


public class MainActivity extends AppCompatActivity {

    private WebView wvBrowser;
    private EditText etUrl;
    private Button btnGo, btnBack, btnForward;
    private ListView lvHistory;

    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;
    private ArrayList<String> historyList;
    private ArrayAdapter<String> historyAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 在 setContentView 之前请求窗口特性
        getWindow().requestFeature(Window.FEATURE_PROGRESS);
        setContentView(R.layout.activity_main);

        // 初始化视图
        wvBrowser = findViewById(R.id.wvBrowser);
        etUrl = findViewById(R.id.etUrl);
        btnGo = findViewById(R.id.btnGo);
        btnBack = findViewById(R.id.btnBack);
        btnForward = findViewById(R.id.btnForward);
        lvHistory = findViewById(R.id.lvHistory);

        // 初始化 SharedPreferences 和历史记录
        sharedPreferences = getSharedPreferences("BrowserHistory", MODE_PRIVATE);
        editor = sharedPreferences.edit();
        historyList = new ArrayList<>();
        loadHistory();

        // 设置历史记录列表的适配器
        historyAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, historyList);
        lvHistory.setAdapter(historyAdapter);

        // 设置 WebView
        wvBrowser.getSettings().setJavaScriptEnabled(true); // 支持 JavaScript
        wvBrowser.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                // 更新进度条
                setProgress(newProgress * 100);
            }
        });

        wvBrowser.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // 在当前 WebView 中加载 URL
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                // 将 URL 添加到历史记录
                if (!historyList.contains(url)) {
                    historyList.add(0, url); // 添加到列表顶部
                    historyAdapter.notifyDataSetChanged();
                }
                etUrl.setText(url);
            }
        });

        // "Go" 按钮点击事件
        btnGo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url = etUrl.getText().toString().trim();
                if (URLUtil.isNetworkUrl(url)) {
                    wvBrowser.loadUrl(url);
                    lvHistory.setVisibility(View.GONE);
                    wvBrowser.setVisibility(View.VISIBLE);
                } else {
                    Toast.makeText(MainActivity.this, "抱歉，您输入的网址有错", Toast.LENGTH_SHORT).show();
                    etUrl.requestFocus();
                }
            }
        });

        // "Back" 按钮点击事件
        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (wvBrowser.canGoBack()) {
                    wvBrowser.goBack();
                } else {
                    Toast.makeText(MainActivity.this, "抱歉，您现在不能后退", Toast.LENGTH_SHORT).show();
                }
            }
        });

        // "Forward" 按钮点击事件
        btnForward.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (wvBrowser.canGoForward()) {
                    wvBrowser.goForward();
                } else {
                    Toast.makeText(MainActivity.this, "抱歉，您现在不能前进", Toast.LENGTH_SHORT).show();
                }
            }
        });

        // 历史记录列表项点击事件
        lvHistory.setOnItemClickListener((parent, view, position, id) -> {
            String url = historyList.get(position);
            etUrl.setText(url);
            wvBrowser.loadUrl(url);
            lvHistory.setVisibility(View.GONE);
            wvBrowser.setVisibility(View.VISIBLE);
        });
    }

    private void loadHistory() {
        Set<String> historySet = sharedPreferences.getStringSet("history", new HashSet<>());
        historyList.addAll(historySet);
    }

    private void saveHistory() {
        Set<String> historySet = new HashSet<>(historyList);
        editor.putStringSet("history", historySet);
        editor.apply();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        saveHistory();
    }

    @Override
    public void onBackPressed() {
        if (wvBrowser.getVisibility() == View.VISIBLE) {
            wvBrowser.setVisibility(View.GONE);
            lvHistory.setVisibility(View.VISIBLE);
        } else {
            super.onBackPressed();
        }
    }
}
